package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


// 购物车
@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;

    @Override
    public Cart add(Cart cartParam) {
        //select * from shopping_cart where user_id = ? and (setmeal_id = ? | dish_id = ?)
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        Long userId = UserHolder.get().getId();
        //用户id
        qw.eq(Cart::getUserId,userId);
        //菜品id
        qw.eq(cartParam.getDishId() != null,Cart::getDishId,cartParam.getDishId());
        //套餐id
        qw.eq(cartParam.getSetmealId() != null,Cart::getSetmealId,cartParam.getSetmealId());
        Cart cart = cartMapper.selectOne(qw);

        //判断是否有这条购物车信息
        if(cart != null){
            //如果有,购物车中物品数量+1
            cart.setNumber(cart.getNumber()+1);
            //更新数据库
            cartMapper.updateById(cart);
        }else {
            //如果没有
            cart = cartParam;
            cart.setCreateTime(new Date());//创建时间
            cart.setUserId(userId);//用户id
            cart.setNumber(1);//菜品数量
            cartMapper.insert(cart);

        }

        return cart;
    }

    //查询购物车内数据
    @Override
    public List<Cart> list() {
        //select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId,UserHolder.get().getId());
        return cartMapper.selectList(qw);
    }

    //清空购物车
    @Override
    public void delete() {
        //delete from shopping_cart where user_id =?
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId,UserHolder.get().getId());
        cartMapper.delete(qw);
    }

    //删除购物车部分数据
    @Override
    public Cart deleteByDishId(Cart cartParam) {
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        //userId
        qw.eq(Cart::getUserId,UserHolder.get().getId());
        //setmealId
        qw.eq(cartParam.getSetmealId()!= null,Cart::getSetmealId,cartParam.getSetmealId());
        //dishId
        qw.eq(cartParam.getDishId()!=null,Cart::getDishId,cartParam.getDishId());

        Cart cart = cartMapper.selectOne(qw);

        cart.setNumber(cart.getNumber()-1);

        //判断菜品减1是否为0
        if(cart.getNumber()==0){
            cartMapper.deleteById(cart);
        }else{
            cartMapper.updateById(cart);
        }
        return cart;
    }
}
